package io.lckgroup.modules.lck.controller;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.gridfs.model.GridFSFile;
import io.lckgroup.common.exception.BackException;
import io.lckgroup.common.utils.PageUtils;
import io.lckgroup.common.utils.R;
import io.lckgroup.modules.lck.entity.CommonAdEntity;
import io.lckgroup.modules.lck.service.CommonAdService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsCriteria;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;


/**
 * 广告表
 *
 * @author srq
 * @email siruiqi@siruiqi.com
 * @date 2020-01-19 19:14:38
 */
@RestController
@RequestMapping("diancan/commonad")
public class CommonAdController {
    @Autowired
    private CommonAdService commonAdService;

    @Value("${backend.mongo.prefix}")
    private String prefix;

    @Autowired
    private GridFsOperations gridFsOperations;

    @Autowired
    private GridFsTemplate gridFsTemplate;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @RequiresPermissions("diancan:commonad:save")
    public R upload(@RequestParam("file") MultipartFile file, CommonAdEntity commonAdEntity) throws Exception {
        if (commonAdService.list().size() != 0) {
            return R.error("只能存在一条广告");
        }
        if (file.isEmpty()) {
            throw new BackException("上传文件不能为空");
        }
        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //调用MongoDB存储
        DBObject metaData = new BasicDBObject();
        metaData.put("c_time", System.currentTimeMillis());
        String fileName = UUID.randomUUID().toString() + suffix;
        InputStream inputStream = new ByteArrayInputStream(file.getBytes());
        try {
            gridFsTemplate.store(inputStream, fileName, suffix, metaData);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BackException("上传文件失败，请重试");
        }
        String url = prefix + fileName;

        //保存文件信息
        commonAdEntity.setPhotoUrl(url);
        commonAdService.save(commonAdEntity);

        return R.ok().put("url", url);
    }

    /**
     * 删除文件
     */
    @PostMapping("/delete/{id}")
    @RequiresPermissions("diancan:commonad:delete")
    public R delete(@RequestBody Long id) {
        CommonAdEntity commonAdEntities = commonAdService.getById(id);
        String fileName = commonAdEntities.getPhotoUrl().substring(prefix.length());
        Optional<GridFSFile> optionalCreated = maybeLoadFile(fileName);
        if (optionalCreated.isPresent()) {
            gridFsTemplate.delete(getFilenameQuery(fileName));
            commonAdService.removeById(id);
        } else {
            return R.error("删除失败");
        }
        return R.ok("删除成功");
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("diancan:commonad:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = commonAdService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("diancan:commonad:info")
    public R info(@PathVariable("id") Long id) {
        CommonAdEntity commonAd = commonAdService.getById(id);

        return R.ok().put("commonAd", commonAd);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("diancan:commonad:update")
    public R update(@RequestBody CommonAdEntity commonAd) {
        commonAdService.updateById(commonAd);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("diancan:commonad:delete")
    public R delete(@RequestBody Long[] ids) {
        commonAdService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    private Optional<GridFSFile> maybeLoadFile(String name) {
        GridFSFile file = gridFsOperations.findOne(getFilenameQuery(name));
        return Optional.ofNullable(file);
    }

    private static Query getFilenameQuery(String name) {
        return Query.query(GridFsCriteria.whereFilename().is(name));
    }

}
